import 'dart:developer';
import 'package:sports_new/base/base_controller.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:sports_new/entity/home/news_class2_entity.dart';
import 'package:sports_new/server/api/home_api.dart';
import 'package:sports_new/utils/utils.dart';

import '../../utils/user.dart';

class HomeChannelFilterLogic extends BaseController {
  bool _editable = false;
  final scrollController = ApmScrollController();
  late final contentController =
      ListObserverController(controller: scrollController);
  List<NewsClass2Entity> fixedChannels = [];
  List<NewsClass2Entity> myChannels = [];
  List<NewsClass2Entity> otherChannels = [];
  Map<int, NewsClass2Entity> _myChannelsMap = {};
  List<NewsClass2Entity> allChannels = [];

  bool get editable => _editable;
  Map<int, NewsClass2Entity> get myChannelsMap => _myChannelsMap;
  // String get selectCountry => _selectCountry;
  // ChannelAreaEntity? get area => _area;

  // set area(ChannelAreaEntity? value) {
  //   _area = value;
  //   update();
  // }

  // set selectCountry(String value) {
  //   _selectCountry = value;
  //   update();
  // }

  set myChannelsMap(Map<int, NewsClass2Entity> value) {
    _myChannelsMap = value;
    update();
  }

  set editable(bool value) {
    _editable = value;
    update();
  }

  @override
  onReady() async {
    await requestMyChannels();
    await requestChannelsAll();
  }

  void updateChannelsMap() => myChannelsMap = myChannels
      .asMap()
      .map((key, value) => MapEntry(value.categoryId ?? 0, value));

  Future requestMyChannels() async {
    final channels = await HomeApi.getNewsClasses2(!User.isLogin);
      log("get my league channels ${channels.map((e) => e.id)}");
    myChannels = channels;
    updateChannelsMap();
    update();
  }

  Future requestChannelsAll() async {
    final result = await HomeApi.getNewsClasses2(true);
    if (result.isNotEmpty) {
      // otherChannels = [];
      fixedChannels = result.filter((item) => item.fixed == 1);
      allChannels = result;
      for (var channel in allChannels) {
        if (!myChannels.any((element) => element.id == channel.id) &&
            channel.fixed == 0) {
          otherChannels.add(channel);
        }
      }
      update();
    }
  }

  Future updateMyChannels() async {
    List<NewsClass2Entity> channels = [];
    channels.addAll(fixedChannels);
    channels.addAll(myChannels);
    final r =
        await HomeApi.updateNewsClasses(channels.map((e) => e.id!).toList());
  }

  Future clickEdit() async {
    if (User.isLogin) {
      editable = !editable;
      if (!editable) {
        updateMyChannels();
      }
    } else {
      await User.needLogin(() => null);
      requestMyChannels();
    }
  }
}
